package com.sunbim.rsrv.common.response;

import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(basePackages = "com.sunbim.rsrv")
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // true 开启aop
        return true;
    }

    @Override
    // before body write 在body写入之前 浏览器传输的数据 body json
    // 对每个controller return的东西做一个包装
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (body instanceof String) {
            return JSONUtil.toJsonStr(R.success(body));
        }

        if (body instanceof R) {
            return body;
        }

        return R.success(body);
    }
}
